
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇游戏</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            background: #f0f0f0;
        }
        #game-container {
            display: flex;
            gap: 20px;
            margin-top: 20px;
        }
        #canvas {
            border: 2px solid #333;
            background: #fff;
        }
        #control-panel {
            width: 200px;
            padding: 15px;
            background: #e9e9e9;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        button {
            padding: 8px 15px;
            margin: 5px 0;
            background: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .score-display {
            font-size: 18px;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <h1>贪吃蛇游戏</h1>
    <div id="game-container">
        <canvas id="canvas" width="400" height="400"></canvas>
        <div id="control-panel">
            <div class="score-display">得分: <span id="score">0</span></div>
            <button id="start-btn">开始游戏</button>
            <button id="pause-btn">暂停游戏</button>
            <button id="restart-btn">重新开始</button>
            <div>
                <label for="difficulty">难度:</label>
                <select id="difficulty">
                    <option value="150">简单</option>
                    <option value="100" selected>中等</option>
                    <option value="50">困难</option>
                </select>
            </div>
            <div class="game-info">
                <h3>操作说明:</h3>
                <p>方向键/WASD控制移动</p>
                <p>P键暂停，C键继续</p>
            </div>
        </div>
    </div>

    <script>
        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        const scoreDisplay = document.getElementById('score');
        const startBtn = document.getElementById('start-btn');
        const pauseBtn = document.getElementById('pause-btn');
        const restartBtn = document.getElementById('restart-btn');
        const difficultySelect = document.getElementById('difficulty');

        const gridSize = 20;
        const gridCount = canvas.width / gridSize;
        let snake = [];
        let food = {};
        let direction = 'right';
        let nextDirection = 'right';
        let gameInterval;
        let score = 0;
        let gameRunning = false;

        function initGame() {
            snake = [
                {x: 5, y: 10},
                {x: 4, y: 10},
                {x: 3, y: 10}
            ];
            generateFood();
            direction = 'right';
            nextDirection = 'right';
            score = 0;
            scoreDisplay.textContent = score;
        }

        function generateFood() {
            const maxPos = gridCount - 1;
            food = {
                x: Math.floor(Math.random() * maxPos),
                y: Math.floor(Math.random() * maxPos)
            };
            
            // 确保食物不会生成在蛇身上
            for (let segment of snake) {
                if (segment.x === food.x && segment.y === food.y) {
                    return generateFood();
                }
            }
        }

        function draw() {
            // 清空画布
            ctx.fillStyle = '#fff';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            // 绘制食物
            ctx.fillStyle = '#f00';
            ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize);
            
            // 绘制蛇
            snake.forEach((segment, index) => {
                ctx.fillStyle = index === 0 ? '#4CAF50' : '#8BC34A';
                ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
                ctx.strokeStyle = '#fff';
                ctx.strokeRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
            });
        }

        function update() {
            // 更新蛇的位置
            const head = {x: snake[0].x, y: snake[0].y};
            
            switch (direction) {
                case 'up':
                    head.y -= 1;
                    break;
                case 'down':
                    head.y += 1;
                    break;
                case 'left':
                    head.x -= 1;
                    break;
                case 'right':
                    head.x += 1;
                    break;
            }
            
            // 检查碰撞
            if (head.x < 0 || head.x >= gridCount || head.y < 0 || head.y >= gridCount || 
                snake.some(segment => segment.x === head.x && segment.y === head.y)) {
                gameOver();
                return;
            }
            
            // 添加新头部
            snake.unshift(head);
            
            // 检查是否吃到食物
            if (head.x === food.x && head.y === food.y) {
                score += 10;
                scoreDisplay.textContent = score;
                generateFood();
            } else {
                // 如果没有吃到食物，移除尾部
                snake.pop();
            }
            
            // 更新方向
            direction = nextDirection;
        }

        function gameOver() {
            clearInterval(gameInterval);
            gameRunning = false;
            alert(`游戏结束! 你的得分是: ${score}`);
        }

        function startGame() {
            if (gameRunning) return;
            initGame();
            gameRunning = true;
            const speed = parseInt(difficultySelect.value);
            gameInterval = setInterval(() => {
                update();
                draw();
            }, speed);
        }

        function pauseGame() {
            if (!gameRunning) return;
            clearInterval(gameInterval);
            gameRunning = false;
        }

        // 事件监听
        startBtn.addEventListener('click', startGame);
        pauseBtn.addEventListener('click', pauseGame);
        restartBtn.addEventListener('click', () => {
            pauseGame();
            startGame();
        });

        document.addEventListener('keydown', (e) => {
            switch (e.key) {
                case 'ArrowUp':
                case 'w':
                case 'W':
                    if (direction !== 'down') nextDirection = 'up';
                    break;
                case 'ArrowDown':
                case 's':
                case 'S':
                    if (direction !== 'up') nextDirection = 'down';
                    break;
                case 'ArrowLeft':
                case 'a':
                case 'A':
                    if (direction !== 'right') nextDirection = 'left';
                    break;
                case 'ArrowRight':
                case 'd':
                case 'D':
                    if (direction !== 'left') nextDirection = 'right';
                    break;
                case 'p':
                case 'P':
                    pauseGame();
                    break;
                case 'c':
                case 'C':
                    startGame();
                    break;
                case 'r':
                case 'R':
                    pauseGame();
                    startGame();
                    break;
            }
        });

        // 初始绘制
        initGame();
        draw();
    </script>
</body>
</html>
